//
//  LoginForThirdManger.m
//  LoginRegisterModule
//
//  Created by InitialC on 16/11/3.
//  Copyright © 2016年 InitialC. All rights reserved.
//

#import "LoginForThirdManger.h"
#import <SVProgressHUD/SVProgressHUD.h>

#import <ShareSDKConnector/ShareSDKConnector.h>
#import <ShareSDKExtension/SSEThirdPartyLoginHelper.h>
#import <ShareSDKExtension/ShareSDK+Extension.h>

#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import <WXApi.h>
#import <WeiboSDK.h>
#import <SMS_SDK/SMSSDK+ContactFriends.h>

@implementation LoginForThirdManger

+ (instancetype)shareInstcetype {
    static id object = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        object = [[self alloc] init];
    });
    return object;
    
}

#pragma mark - 三方登录
// TODO: --
+ (void)initialSMShare:(NSDictionary *)keyDict {
    if (keyDict == nil) {
        return;
    }
    ///微信第三方登录
    NSString *kWeiXinAppKey      = keyDict[@"wxKey"];
    NSString *kWeiXinAppSecret   = keyDict[@"wxSecret"];
    
    ///微博第三方登录
    NSString *kWeiBoAppId          = keyDict[@"wbID"];
    NSString *kWeiBoAppSecret      = keyDict[@"wbSecret"];
    NSString *kWeiBoAppRedirectURL = keyDict[@"wbRedirectURL"];
    
    ///QQ第三方登录
    NSString *kQQAppKey          = keyDict[@"qqKey"];
    NSString *kQQAppSecret       = keyDict[@"qqSecret"];
//    [SMSSDK registerApp:@"***"
//             withSecret:@"***"];
    //初始化应用，appKey和appSecret从后台申请得
    NSLog(@"结果==%@ \n随机取key==%@, %@, %@", keyDict, kWeiXinAppKey, kWeiBoAppId, kQQAppKey);
    [SMSSDK enableAppContactFriends:NO];
    [ShareSDK registerActivePlatforms:@[@(SSDKPlatformTypeSMS),
                                        @(SSDKPlatformTypeWechat),
                                        @(SSDKPlatformTypeQQ),
                                        @(SSDKPlatformTypeSinaWeibo),
                                        @(SSDKPlatformSubTypeQZone),
                                        @(SSDKPlatformTypeCopy),
                                        @(SSDKPlatformSubTypeWechatTimeline)]
                             onImport:^(SSDKPlatformType platformType) {
                                 switch (platformType) {
                                     case SSDKPlatformTypeWechat:
                                         [ShareSDKConnector connectWeChat:[WXApi class]];
                                         break;
                                     case SSDKPlatformTypeQQ:
                                         [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
                                         break;
                                     case SSDKPlatformTypeSinaWeibo:
                                         [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                                         break;
                                     default:
                                         break;
                                 }
                             }
                      onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo) {
                          switch (platformType) {
                              case SSDKPlatformTypeWechat:
                                  [appInfo SSDKSetupWeChatByAppId:kWeiXinAppKey
                                                        appSecret:kWeiXinAppSecret];
                                  break;
                              case SSDKPlatformTypeQQ:
                                  [appInfo SSDKSetupQQByAppId:kQQAppKey
                                                       appKey:kQQAppSecret
                                                     authType:SSDKAuthTypeBoth];
                                  break;
                              case SSDKPlatformTypeSinaWeibo:
                                  [appInfo SSDKSetupSinaWeiboByAppKey:kWeiBoAppId
                                                            appSecret:kWeiBoAppSecret
                                                          redirectUri:kWeiBoAppRedirectURL
                                                             authType:SSDKAuthTypeBoth];
                                  break;
                              default:
                                  break;
                          }
                      }];
}
//- (instancetype)init {
//    self = [super init];
//    if (self) {
//    }
//    return self;
//}

+ (void)loginWithPlatformType:(SSDKPlatformType)type withBlock:(void (^)(SSDKUser *, NSError *, SSDKResponseState))block {
    [SVProgressHUD setMinimumDismissTimeInterval:1.0];
    [SSEThirdPartyLoginHelper loginByPlatform:type onUserSync:^(SSDKUser *user, SSEUserAssociateHandler associateHandler) {
        
        //在此回调中可以将社交平台用户信息与自身用户系统进行绑定，最后使用一个唯一用户标识来关联此用户信息。
        //在此示例中没有跟用户系统关联，则使用一个社交用户对应一个系统用户的方式。将社交用户的uid作为关联ID传入associateHandler。
        associateHandler (user.uid, user, user);
        NSLog(@"dd %@",user.rawData);
        NSLog(@"ddd %@",user.credential);
        //        NSLog(@"AAAA %@", user.credential.uid);
        block(user, nil, SSDKResponseStateSuccess);
        
    } onLoginResult:^(SSDKResponseState state, SSEBaseUser *user, NSError *error) {
        
        if (state == SSDKResponseStateSuccess) {
            
        } else if (state == SSDKResponseStateFail || state == SSDKResponseStateCancel) {
            block(nil, error, state);
            if (state == SSDKResponseStateFail || error != nil) {
                [SVProgressHUD showErrorWithStatus:@"登录失败"];
            } else if (state == SSDKResponseStateCancel) {
                [SVProgressHUD showInfoWithStatus:@"取消登录"];
            }
        }
        
    }];
}

#pragma mark - 短信验证
+ (void)getVerificationCodeByMethod:(SMSGetCodeMethod)type withPhoneInformation:(NSDictionary *)phoneInfo withBlock:(void (^)(NSError *))block {
    // 得到验证码
    [SMSSDK getVerificationCodeByMethod:type phoneNumber:phoneInfo[@"phone"] zone:phoneInfo[@"zone"] result:^(NSError *error) {
        if (!error) {
            NSLog(@"获取验证码成功");
            block(nil);
        }else {
            NSLog(@"错误信息: %@", error);
            block(error);
        }
    }];
}
+ (void)commitVerificationCode:(NSString *)verifyCode withPhoneZone:(NSDictionary *)phoneZone withBlock:(void (^)(NSError *))block {
    // 提交验证码
    [SMSSDK commitVerificationCode:verifyCode phoneNumber:phoneZone[@"phone"] zone:phoneZone[@"zone"] result:^(NSError *error) {
        block(error);
    }];
    
}
#pragma mark - 内测验证
+ (void)betaVerification:(NSString *)phoneNumber testURL:(NSString *)url completion:(void (^)(BOOL, NSError *))block {
    NSMutableURLRequest *testRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    testRequest.HTTPMethod = @"post";
//    [testRequest setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    NSURLSession *sessions = [NSURLSession sharedSession];
    NSURLSessionTask *sessionTask = [sessions dataTaskWithRequest:testRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data != nil) {
            NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            __autoreleasing NSError *error = nil;
            id tempDic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
            if (error != nil) {
                block(NO, error);
                return;
            }
            NSLog(@"内测测试结果==%@", tempDic);
            block(YES, nil);
        } else if (error != nil){
            block(NO, error);
        }
    }];
    [sessionTask resume];
}

#pragma mark - 分享
+ (void)platShare:(NSDictionary *)dic withBlock:(void (^)(BOOL))block
{
    /**
     * 在定制平台内容分享中，除了设置共有的分享参数外，还可以为特定的社交平台进行内容定制，
     * 如：其他平台分享的内容为“分享内容”，但新浪微博需要在原有的“分享内容”文字后面加入一条链接，则可以如下做法：
     **/
    
    //创建分享参数
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    
    //    NSArray* imageArray = @[dic[@"image"]];
    SSDKImage *image = nil;
    if ([dic[@"image"] isKindOfClass:[NSString class]]) {
        image = [[SSDKImage alloc] initWithURL:[NSURL URLWithString:dic[@"image"]]];
    } else if ([dic[@"image"] isKindOfClass:[UIImage class]] ) {
        NSArray *productImagePaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *productImageFilePath = [[productImagePaths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"memoryForWeChat.jpeg"]];
        [UIImageJPEGRepresentation(dic[@"image"], 0.8) writeToFile:productImageFilePath atomically:YES];
        NSURL *productImageFileUrl = [NSURL fileURLWithPath:productImageFilePath];
        image = [[SSDKImage alloc] initWithURL:productImageFileUrl];
    } else if ([dic[@"image"] isKindOfClass:[NSURL class]]) {
        image = [[SSDKImage alloc] initWithURL:dic[@"image"]];
    }
    if (image) {
        int intType = [dic[@"contentType"] intValue];
        if ([dic[@"type"] intValue] == 1) {
            if (![ShareSDK isClientInstalled:SSDKPlatformTypeSinaWeibo]) {
                [SVProgressHUD setMinimumDismissTimeInterval:1.0];
                [SVProgressHUD showErrorWithStatus:@"分享失败, 请安装微博客户端"];
                return;
            }
            [shareParams SSDKSetupSinaWeiboShareParamsByText:dic[@"message"]
                                                       title:dic[@"title"]
                                                       image:image url:dic[@"url"]
                                                    latitude:39.917 longitude:116.392
                                                    objectID:@"memoryshareid"
                                                        type:intType];
        } else {
            [shareParams SSDKSetupShareParamsByText:dic[@"message"]
                                             images:image
                                                url:dic[@"url"]
                                              title:dic[@"title"]
                                               type:intType];
        }
        [shareParams SSDKEnableUseClientShare];
        //进行分享
        [ShareSDK share:[dic[@"type"] intValue]
             parameters:shareParams
         onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
             
             switch (state) {
                 case SSDKResponseStateSuccess:
                 {
                     //                     UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                     //                                                                         message:nil
                     //                                                                        delegate:nil
                     //                                                               cancelButtonTitle:@"确定"
                     //                                                               otherButtonTitles:nil];
                     //                     [alertView show];
                     block(YES);
                     break;
                 }
                 case SSDKResponseStateFail:
                 {
                     
                     [SVProgressHUD showErrorWithStatus:@"分享失败"];
                     [SVProgressHUD setMinimumDismissTimeInterval:1.0];
//                                          UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享失败"
//                                                                                              message:@""
//                                                                                             delegate:nil
//                                                                                    cancelButtonTitle:@"确定"
//                                                                                    otherButtonTitles:nil];
//                                          [alertView show];
                     block(NO);
                     break;
                 }
                 case SSDKResponseStateCancel:
                 {
                     //                     UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享已取消"
                     //                                                                         message:nil
                     //                                                                        delegate:nil
                     //                                                               cancelButtonTitle:@"确定"
                     //                                                               otherButtonTitles:nil];
                     //                     [alertView show];
                     block(NO);
                     break;
                 }
                 default:
                     break;
             }
             
             
         }];
    }
}


@end
